package com.walnut.lom_system.common.util;

import com.walnut.lom_system.common.lang.Const;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenhetao
 * @version 1.0
 * @className EmailBuildUtil
 * @description 用于构建邮件（忘记密码和注册邮件）
 * @date 2022/1/26 04:34
 */
@Component
public class EmailBuildUtil {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    /**
     * 构建邮件
     * @param receiver 收件人邮箱
     * @param code 验证码
     * @param type 邮件类型
     * @return 邮件内容的String形式
     * @throws IOException
     * @throws TemplateException
     */
    public String buildEmail(String receiver, String code, int type) throws IOException, TemplateException {
        Map<String, Object> map = new HashMap<String, Object>(2);
        //传入参数
        map.put("receiver", receiver);
        map.put("code", code);
        Template template = null;
        if (type == Const.MAIL_FORGET) {
            //获取忘记密码的邮件模版
            template = freeMarkerConfigurer.getConfiguration().getTemplate("forgetEmail.html");
        }
        else if (type == Const.MAIL_REGISTER) {
            //获取注册的邮件模版
            template = freeMarkerConfigurer.getConfiguration().getTemplate("registerEmail.html");
        }
        else {
            //获取默认的邮件模版，传参错误等非正确构建模板的情况下
            template = freeMarkerConfigurer.getConfiguration().getTemplate("test.html");
        }
        //构建邮件并返回
        return FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
    }
}
